﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla.Data;
using System.Data.SqlClient;
using Csla.Core;
using Csla.Server;
using System.Collections;

namespace Csla
{
    [Serializable]
    public class GBusinessListBase<T, C> : BusinessListBase<T, C>
        , Csla.OpenExpressApp.IEntityStatus
        where T : GBusinessListBase<T, C>
        where C : Core.IEditableBusinessObject
    {
        protected virtual string ConnectionString
        {
            get
            {
                return "BusinessDBName";
            }
        }

        protected void RemoveChildOnLoad(BusinessBase child)
        {
            (this as IEditableCollection).RemoveChild(child);
            ((this as IEditableCollection).GetDeletedList() as IList).Remove(child);
        }

        protected override void RemoveItem(int index)
        {
            C child = this[index];
            base.RemoveItem(index);
            if (child is ITreeNode)
            {
                (child as ITreeNode).ParentNode = null;
            }
        }

        [Transactional(TransactionalTypes.TransactionScope)]
        protected override void DataPortal_Update()
        {
            //using (var ctx = ConnectionManager<SqlConnection>.GetManager(this.ConnectionString))
            {
                foreach (var child in DeletedList)
                {
                    DataPortal.Update(child);
                }
                DeletedList.Clear();
                foreach (ISavable item in this)
                {
                    item.Save();
                    (item as IDataPortalTarget).MarkOld();
                }
            }
        }

        #region IEntityStatus Members

        public void MarkClean()
        {
            //由于外界已经间接实现了这个功能。
            //所以暂时不需要添加这块代码了。不过不用删除。可能以后会用到。

            //this.DeletedList.Clear();

            //foreach (C child in this)
            //{
            //    if (child.IsDirty)
            //    {
            //        var childEntity = child as Csla.OpenExpressApp.IEntityStatus;
            //        if (childEntity != null)
            //        {
            //            childEntity.MarkClean();
            //        }
            //    }
            //}
        }

        #endregion

        public new IParent Parent
        {
            get
            {
                return base.Parent;
            }
        }
    }
}
